﻿using System;
using System.Collections.Generic;

namespace Codemonk.Soya
{
    public sealed class StringConverter : IStringConverter
    {
        private static Dictionary<Type, Func<string, object, object>> prasers = new Dictionary<Type, Func<string, object, object>>
        {
            { typeof(string),(str,d)=>str},
            { typeof(bool),(str,d)=>SafetyPraser(str,bool.Parse)},
            { typeof(int),(str,d)=>SafetyPraser(str,int.Parse)},
            { typeof(double),(str,d)=>SafetyPraser(str,double.Parse)},
            { typeof(float),(str,d)=>SafetyPraser(str,float.Parse)},
            { typeof(decimal),(str,d)=>SafetyPraser(str,decimal.Parse)},
        };

        private static T SafetyPraser<T>(string input, Func<string, T> praser)
        {
            return praser(input);
        }
        public object As(Type type, string input, object defaultValue = null)
        {
            Func<string, object, object> praser;
            if (prasers.TryGetValue(type, out praser))
                return praser(input, defaultValue);
            return defaultValue;
        }
    }
}
